<!-- <route lang="yaml">
  meta:
    enabled: false
  </route> -->

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { GetDataDetail, PostListAdd, PutListEdit } from '@/api/modules/shareCardConfiguration.ts'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const imgDomain = 'https://img1.eprhan.cc'

const ruleFormRef = ref<FormInstance>()
const ruleForm: any = ref({
  title: '',
  pagepath: '',
  msgtype: 78,
  desp: '',
  weappIconUrl: '',
  cardPicUrl: '',
})

const typeArr = [
  { value: 2, label: '文本' },
  { value: 13, label: '链接' },
  { value: 78, label: '小程序' },
  { value: 101, label: '外部联系人图片' },
  { value: 104, label: 'gif表情' },
  { value: 141, label: '视频号' },
]

// 存放截取后的图片路径
const UrlFrom = ref({
  weappIconUrl: '',
  cardPicUrl: '',
})
const rules = reactive({
  pagepath: [
    { required: true, message: '请输入小程序页面地址', trigger: 'blur' },
  ],
  cardPicUrl: [
    { required: true, message: '请上传图片', trigger: 'blur' },
  ],
})

function handleUploadSuccess(key: keyof typeof UrlFrom.value, url: string) {
  ruleForm.value[key] = imgDomain + url
  UrlFrom.value[key] = url
}

function validatePagePath(pagepath: string) {
  // 检查pagepath是否包含参数
  const hasParams = pagepath.includes('?')

  if (hasParams) {
    const parts = pagepath.split('?')
    const addressPart = parts[0]

    // 检查地址部分是否以html结尾
    if (!addressPart.endsWith('.html')) {
      return `${addressPart}.html?${parts[1]}`
    }
    else {
      return pagepath
    }
  }
  else {
    if (!pagepath.endsWith('.html')) {
      return `${pagepath}.html`
    }
    else {
      return pagepath
    }
  }
}

const id = route.query.id as string
// 编辑
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      // 处理传入地址
      if (ruleForm.value.pagepath !== '') {
        ruleForm.value.pagepath = validatePagePath(ruleForm.value.pagepath)
      }

      if (id) {
        PutListEdit(ruleForm.value).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({
              name: 'shareCardConfigurationIndex',
            })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`编辑失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`编辑失败。${errorStr}`)
            }
          }
        })
      }
      else {
        PostListAdd(ruleForm.value).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.EmptyEnterpriseWeChat()
            router.push({
              name: 'shareCardConfigurationIndex',
            })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`添加失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`添加失败。${errorStr}`)
            }
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}
function extractUrlPart(url: string) {
  return url.replace(/https?:\/\/[^/]+/, '')
}

watch(ruleForm, (newValue) => {
  detailData.RememberEnterpriseWeChat(newValue)
}, { deep: true })

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        UrlFrom.value.weappIconUrl = extractUrlPart(ruleForm.value.weappIconUrl)
        UrlFrom.value.cardPicUrl = extractUrlPart(ruleForm.value.cardPicUrl)
      }
    })
  }
  else {
    ruleForm.value = detailData.GetEnterpriseWeChatData()
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <div style="display: grid; grid-template-columns: 2fr 1fr; margin-top: -15px;">
        <PageMain title="基础信息">
          <ElRow :gutter="20">
            <ElCol :md="12">
              <ElFormItem label="标题" prop="title">
                <el-input v-model="ruleForm.title" style="width: 400px;" placeholder="请输入标题" />
              </ElFormItem>
            </ElCol>
            <ElCol :md="12">
              <ElFormItem v-if="ruleForm.msgtype !== 2" label="小程序页面地址" prop="pagepath">
                <el-input v-model="ruleForm.pagepath" style="width: 400px;" placeholder="请输入跳转地址">
                  <template #append>
                    .html
                  </template>
                </el-input>
              </ElFormItem>
            </ElCol>
            <ElCol :md="24">
              <ElFormItem label="类型" prop="msgtype">
                <el-select v-model="ruleForm.msgtype" placeholder="请选择" style="width: 400px;">
                  <el-option v-for="item in typeArr" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </ElFormItem>
            </ElCol>
            <ElCol :md="12">
              <ElFormItem label="小图标" prop="weappIconUrl">
                <ImageUpload
                  :ext="['jpg', 'png']" :size="5" :url="UrlFrom.weappIconUrl"
                  @on-success="(imgUrl) => handleUploadSuccess('weappIconUrl', imgUrl)"
                />
              </ElFormItem>
            </ElCol>
            <ElCol v-if="ruleForm.msgtype === 78 || ruleForm.msgtype === 101" :md="12">
              <ElFormItem :label="ruleForm.msgtype === 78 ? '卡片的图片地址' : ruleForm.msgtype === 101 ? '图片地址' : ''" prop="cardPicUrl">
                <ImageUpload
                  :ext="['jpg', 'png']" :size="5" :url="UrlFrom.cardPicUrl"
                  @on-success="(imgUrl) => handleUploadSuccess('cardPicUrl', imgUrl)"
                />
              </ElFormItem>
            </ElCol>
            <ElCol v-if="ruleForm.msgtype === 2 || ruleForm.msgtype === 13 || ruleForm.msgtype === 78" :md="12">
              <ElFormItem :label="ruleForm.msgtype === 2 ? '文本内容' : ruleForm.msgtype === 13 ? '链接地址' : ruleForm.msgtype === 78 ? '小程序描述' : ''">
                <el-input
                  v-model="ruleForm.desp"
                  style="width: 400px;"
                  :type="ruleForm.msgtype === 2 ? 'textarea' : ''"
                  :autosize="{ minRows: 4, maxRows: 10 }"
                />
              </ElFormItem>
            </ElCol>
          </ElRow>
        </PageMain>
        <PageMain title="预览">
          <div v-if="ruleForm.msgtype === 78" class="card">
            <div class="card-header">
              <el-image style="width: 30px; height: 30px;" :src="ruleForm.weappIconUrl" fit="fill" />
              <span>{{ ruleForm.title }}</span>
            </div>
            <div class="card-centent">
              <p>{{ ruleForm.desp }}</p>
              <el-image style="width: 260px; height: 260px;" :src="ruleForm.cardPicUrl" fit="fill" />
            </div>
            <div style="font-size: 12px;">
              小程序
            </div>
          </div>
        </PageMain>
      </div>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-date-editor) {
  width: 100%;
}

.tag {
  margin-left: 10px;
  color: red;
}

.card {
  width: 300px;
  padding: 5px 10px;
  border: 1px solid #ebeef5;

  .card-header {
    display: flex;
    align-items: center;

    span {
      margin-left: 5px;
      font-size: 15px;
      color: darkgray;
    }
  }

  .card-centent {
    p {
      margin: 8px 0;
      font-size: 16px;
    }

    padding-bottom: 10px;
    margin-bottom: 5px;
    border-bottom: 1px solid #ebeef5;
  }
}
</style>
